package org.ytor.core.sysapi.user.repository;

import org.ytor.common.util.Colls;
import org.ytor.common.util.Strs;
import org.ytor.core.sqlflow.BaseRepository;
import org.ytor.core.sqlflow.SQLHelper;
import static org.ytor.core.sqlflow.builder.BuilderWrapper.expr;
import org.ytor.core.sqlflow.builder.select.WhereStage;
import org.ytor.core.sysapi.depart.model.SysDepart;
import org.ytor.core.sysapi.dict.model.SysDict;
import org.ytor.core.sysapi.role.model.SysRole;
import org.ytor.core.sysapi.user.model.SysUser;
import org.ytor.core.sysapi.user.model.SysUserRole;
import org.ytor.core.sysapi.user.resp.SysUserRoleResp;

import java.util.List;

/**
 * created by yangtong on 2025/8/10 00:50:15
 * <br/>
 */
public abstract class SysUserRepository extends BaseRepository<SysUser> {

    public List<SysRole> listAllRoleByUserId(String userId) {

        WhereStage where = SQLHelper.select(SysUserRole::getRoleId)
                .from(SysUserRole.class)
                .where(w -> w.eq(SysUserRole::getUserId, userId));

        return SQLHelper.select()
                .from(SysRole.class)
                .where(w -> w.in(SysRole::getId, where))
                .list();
    }

    public List<SysUserRoleResp> listUserRoles(String userId, String roleName, String roleCode, List<String> departIdList) {
        List<SysUserRoleResp> list = SQLHelper
                .select(SysRole::getRoleCode, SysRole::getRoleName, SysRole::getRoleType)
                .select(SysDepart::getDepartCode, SysDepart::getDepartName)
                .selectRaw("sr.id as roleId", "sd.id as depart_id", "sur.user_id")
                .from(SysRole.class, "sr")
                .leftJoin(SysDepart.class, "sd", on -> on.eq(SysRole::getRoleDepartCode, SysDepart::getDepartCode))
                .leftJoin(SQLHelper.select().from(SysUserRole.class).where(w -> w.eq(SysUserRole::getUserId, userId)), "sur", on -> on.eq(SysRole::getId, expr("sur.role_id")))
                .where(
                        w -> w.like(Strs.isNotEmpty(roleName), SysRole::getRoleName, roleName)
                                .like(Strs.isNotEmpty(roleCode), SysRole::getRoleCode, roleCode)
                                .in(Colls.isNotEmpty(departIdList), SysDepart::getId, departIdList)

                ).list(SysUserRoleResp.class);

        return list;
    }

    public abstract List<SysUser> test(Integer age, String userName, List<String> ids);

    public abstract List<SysDict> dict();

}
